/*
 * $Id$
 *
 * Copyright 2008 HuangHuang. All rights reserved.
 */

package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.IRequestCycle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.crm.model.*;
import com.crm.model.Process;
import com.crm.web.util.Tools;
import com.crm.service.IProcessService;
import com.javaforge.tapestry.spring.annotations.InjectSpring;

import java.util.List;
import java.util.Date;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class Main extends BasePage {

    private static Log log = LogFactory.getLog(Main.class);

    @InjectSpring("processService")
    public abstract IProcessService getProcessService();

    @InjectState("userSession")
    public abstract User getUserSession();

    public abstract void setUserSession(User staff);

    public String getCurrentUser() {
        return "欢迎您，" + getUserSession().getUsername();
    }

    public void userExit(IRequestCycle cycle) {
        String username = getUserSession().getUsername();
        if (username == null) cycle.sendRedirect("app?page=SysPageError&service=page");
        log.info(username + ": Logout!");
        setUserSession(null);
        log.info(username + ": Clear session!");
        cycle.sendRedirect("app?page=Home&service=page");
    }

    public String getRemindInfo() {
        try {
            List processList = getProcessService().getProcessByNoHandle(getUserSession());

            String currentSystemDate = Tools.formatDate(new Date(), Tools.DATEANDTIME);
            currentSystemDate = currentSystemDate.trim();

            int remindInfoNumber = 0;
            for (Object aProcessList : processList) {

                com.crm.model.Process process = (Process) aProcessList;
                String remindDate = process.getRemindDate().trim();

                Date remindDateObj = Tools.getDateByString(remindDate);
                Date currentDateObj = Tools.getDateByString(currentSystemDate);
                int compareValue = remindDateObj.compareTo(currentDateObj);

                if (compareValue <= 0) {
                    remindInfoNumber++;
                }
            }
            log.info(getUserSession().getUsername() + ": Check remind count : " + remindInfoNumber);
            return "(" + remindInfoNumber + ")";
        }
        catch (Exception e) {
            log.warn(getUserSession().getUsername() + ": The exception happened when get remind information. " + e.getMessage());
            e.printStackTrace();
            return "error";
        }
    }

//    public String openRemindInvoke(IRequestCycle cycle) {
//        return "UserRemind";
//    }

    public String openSysHelp() {
        return "SysHelp";
    }

}